package com.envper.common.util;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.envper.common.constant.Constants;
import com.envper.mysql.domain.dto.CaptchaDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
@Slf4j
public class CaptchaUtils {

    private final Integer width = 200;

    private final Integer height = 100;

    private final RedisUtils redisUtils;

    public CaptchaDto getCaptcha(){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(width, height);
        String captchaImageBase64Data = lineCaptcha.getImageBase64Data();
        String key = UUID.randomUUID().toString();
        String captchaCode = lineCaptcha.getCode().toLowerCase();
        redisUtils.setCacheObject(Constants.CAPTCHA + key, captchaCode, 5, TimeUnit.MINUTES);
        return CaptchaDto.builder()
                .captchaKey(key)
                .captchaBase64(captchaImageBase64Data).build();
    }

    public void verifyCaptcha(CaptchaDto captchaDto){
        if(!ObjectUtils.isEmpty(captchaDto)){
            String captchaCode = captchaDto.getCaptchaCode();
            String captchaKey = captchaDto.getCaptchaKey();
            if(StringUtils.hasLength(captchaCode) && StringUtils.hasLength(captchaKey)) {
//                String captchaVerifyCode = (String) redisUtils.getCacheObject(Constants.CAPTCHA + captchaKey);
//                if(StringUtils.hasLength(captchaVerifyCode)){
//                    captchaCode = captchaCode.toLowerCase();
//                    System.out.println("captchaVerifyCode = " + captchaVerifyCode);
//                    if(!captchaVerifyCode.equalsIgnoreCase(captchaCode)){
//                        throw new GlobalException(Status.CAPTCHAERROR, log);
//                    }
//                }else throw new GlobalException(Status.CAPTCHAOVERDUE, log);
            }
        }
    }
}
